# desktop_app/services/crawlers/douyin.py
import requests
import re
import json
from urllib.parse import urlparse

def crawl(video_url):
    """抖音视频爬取方法"""
    try:
        # 这里实现实际的抖音爬取逻辑
        print(f"正在爬取抖音视频: {video_url}")
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/121.0.2277.107 Version/17.0 Mobile/15E148 Safari/604.1'
        }

        # 发送请求获取视频页面
        response = requests.get(video_url, headers=headers)
        video_id = response.url.split("?")[0].strip("/").split("/")[-1]
        share_url = f'https://www.iesdouyin.com/share/video/{video_id}'
        response = requests.get(share_url, headers=headers)
        response.raise_for_status()
        # 使用正则表达式提取视频信息
        pattern = re.compile(
            pattern=r"window\._ROUTER_DATA\s*=\s*(.*?)</script>",
            flags=re.DOTALL
        )
        find_res = pattern.search(response.text)
        if not find_res or not find_res.group(1):
            raise ValueError("parse video json info from html fail")
        
        json_data = json.loads(find_res.group(1).strip())
        data = json_data["loaderData"]["video_(id)/page"]["videoInfoRes"]["item_list"][0]
        video_url = data["video"]["play_addr"]["url_list"][0].replace("playwm", "play")
        
        # 返回结构化数据
        return {
            'success': True,
            'platform': 'douyin',
            'video_id': video_id,
            'download_url': video_url,
            'type': 'video',
            'title': f"抖音视频-{video_id}"
        }
    except Exception as e:
        return {
            'success': False,
            'error': str(e)
        }